#!/bin/bash

#set -ux

# 网络配置
hostname=AnolisOS-test
ip=192.168.20.200
netmask=24
gateway=192.168.20.2
dns1=$gateway
dns2=223.6.6.6
dns3=8.8.8.8
dns4=114.114.114.114

net=$(ip a | grep ens | tail -1 | awk '{print $NF}')

# 辅助函数：检查命令执行结果并输出日志
check_command_status() {
  if [ $? -ne 0 ]; then
    echo "命令执行失败: $1"
    exit 1
  fi
}

# NetworkManager配置
staticIPSet() {
  SERVICE_NAME="NetworkManager"
  if [ $(systemctl is-active $SERVICE_NAME) == "inactive" ]; then
    echo "$SERVICE_NAME 未运行，无法进行配置。请先启动该服务。"
    return
  fi
  echo "$SERVICE_NAME 正在运行。"

  # 修改配置
  nmcli connection modify "$net" \
    ipv4.method 'manual' \
    ipv4.addresses "$ip/$netmask" \
    ipv4.gateway "$gateway" \
    ipv4.dns "$dns1,$dns2,$dns3,$dns4"

  # 重启NetworkManager服务使配置生效
  systemctl restart $SERVICE_NAME
  check_command_status "重启 $SERVICE_NAME 服务"

  echo "查看 ip"
  ip addr show $net
}

# hostname配置
staticHostnameSet() {
  echo "设置hostname $hostname"
  hostnamectl --static set-hostname $hostname

  # 配置IP HOST映射关系
  if grep -qF "$ip $hostname" /etc/hosts; then
    echo "已配置IP HOST映射关系"
  else
    echo "配置IP HOST映射关系"
    sed -i "$ a $ip $hostname" /etc/hosts
  fi
}

#/ sshd配置，禁用DNS反向解析和GSSAPI认证
sshdSet() {
  echo '修改ssh配置'
  sed -i -e '/^#UseDNS/c UseDNS no' \
    -e '/^GSSAPIAuthentication/c GSSAPIAuthentication no' \
    /etc/ssh/sshd_config

  systemctl restart sshd
  check_command_status "重启 sshd 服务"
}

sshdSet
staticHostnameSet
staticIPSet
